package com.peng.leetcode.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * GenerateTrees1
 * 95. 不同的二叉搜索树 II
 * https://leetcode.cn/problems/unique-binary-search-trees-ii/
 * <p>
 * Created on 2022/12/7
 *
 * @author lupeng
 */
public class GenerateTrees1 {
    public List<TreeNode> generateTrees(int n) {
        if (n == 0) {
            return new ArrayList<>();
        }
        return build(1, n);
    }

    List<TreeNode> build(int start, int end) {
        List<TreeNode> result = new ArrayList<>();
        if (start > end) {
            result.add(null);
            return result;
        }
        for (int i = start; i <= end; i++) {
            List<TreeNode> l = build(start, i - 1);
            List<TreeNode> r = build(i + 1, end);
            for (TreeNode ln : l) {
                for (TreeNode rn : r) {
                    TreeNode root = new TreeNode(i);
                    root.left = ln;
                    root.right = rn;
                    result.add(root);
                }
            }
        }
        return result;
    }
}
